const app = getApp()

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


function DoCommand(url, urlParameter, jsonTypeParameter, successFunction, errorFunction,page) {
  var isOne = true;//是否第一次请求
  const baseurl = app.globalData.serverBaseAddr;
  url = baseurl + url;
 // if (urlParameter) {
     urlParameter = GetSign(urlParameter);
     url += "?" + urlParameter
 // }
  wx.request({
    url: url,
    data: jsonTypeParameter,
    method: jsonTypeParameter ? "post" : "get",
    header: {
      //  'content-type': 'application/json' // 默认值
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      //TODO res.statusCode返回状态值处理
      page.setData({
        offline: false
      })
      if (res.statusCode == 200) {
        if (res.data.code == '0') {
          const data = res.data.data;
          if (successFunction) {
            successFunction(data)
          }
        }
        else {
          if (errorFunction) {
            errorFunction(res.data)
          }
          else {
            ErrorMessage()
          }
        }
      }
      else {
        if (errorFunction) {
          errorFunction(res.data)
        }
        else {
          ErrorMessage(res.data)
        }

      }
    },
    fail: function (res) {
      // 防止fail 有时会执行两次，影响渲染
      if (!isOne) {
        return
      }
      page.setData({
        offline:true
      })
      // if (errorFunction) {
      //   errorFunction(res)
      // }
      // else {
      //   ErrorMessage()
      // }
      isOne = false
    }
  })
}
function ErrorMessage(data) {
  console.log(data)
  if(data.code==-1){
    wx.showToast({
      title: "网络连接失败!",
      icon: 'loading',
      duration: 2000
    })
  }
  else{
    wx.showToast({
      title:data.msg,
      icon: 'none',
      duration: 2000
    })
  }
 
}
/**
 * 消息框
 * title 提示的内容
 * icon 图标，有效值 "success", "loading", "none"，默认none
 * duration 提示的延迟时间，单位毫秒，默认：1500
 */
function ShowMessage(title, icon, duration) {
  if (!duration) duration = 1500;
  if (!icon) icon = 'none';
  wx.showToast({
    title: title,
    icon: icon,
    duration: duration
  })
}

function NotVip(){
  ShowMessage("您不是VIP用户，请绑定用户身份");
}

function encodeUTF8(s) {
  var i, r = [], c, x;
  for (i = 0; i < s.length; i++)
    if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
    else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
    else {
      if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
        c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
          r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
      else r.push(0xE0 + (c >> 12 & 0xF));
      r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    };
  return r;
};

// 字符串加密成 hex 字符串
function sha1(s) {
  var data = new Uint8Array(encodeUTF8(s))
  var i, j, t;
  var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
  s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
  for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
  s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
  s[l - 1] = data.length << 3;
  var w = [], f = [
    function () { return m[1] & m[2] | ~m[1] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; },
    function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; }
  ], rol = function (n, c) { return n << c | n >>> (32 - c); },
    k = [1518500249, 1859775393, -1894007588, -899497514],
    m = [1732584193, -271733879, null, null, -1009589776];
  m[2] = ~m[0], m[3] = ~m[1];
  for (i = 0; i < s.length; i += 16) {
    var o = m.slice(0);
    for (j = 0; j < 80; j++)
      w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
        t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
        m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
    for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
  };
  t = new DataView(new Uint32Array(m).buffer);
  for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);

  var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
    return (e < 16 ? "0" : "") + e.toString(16);
  }).join("");

  return hex;
};


function ShowToast(message, options) {
  var defaultOption = {
    title: message
  }

  wx.showToast({
    title: message
  })
} 

function NewGuid() {
  return (S4() + S4() + "_" + S4() + "_" + S4() + "_" + S4() + "_" + S4() + S4() + S4());
}
function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}


function GetSign(parameters) {

  //第一步：索取应用系统私钥key,应用系统私钥key(此值为开发调试临时使用)
  var private_key = "88e02bd6_8d05_8173_90dd_82701f386d23";//

  //第二步：给调用url加上timestamp参数
  var timestamp = (new Date()).valueOf();
  if(parameters==null)
  {
    parameters= "tamp=" + timestamp;
  }
  else{
    parameters += "&tamp=" + timestamp;
  }
 

  //第三步：取出url中的所有参数
  //第四步：把字典值，按key的字母顺序排序，并把key统一转成小写
  parameters = parameters.toLowerCase();
  var parArray = parameters.split("&");
  parArray = parArray.sort();
  // 第五步：把排序后的字典中的key和value串到一起
  parArray = parArray.join("");
  parArray = parArray.replace(/=/g, "");

  //第六步：把私钥key值放加到字符串头部
  parArray = private_key + parArray;

  //第七步：对字符串进行SHA1加密，所得结果既为签名值
  var hash = sha1(parArray)
  //第八步：把签名值追加命令url中
  parameters = parameters + "&signature=" + hash.toLowerCase();
  return parameters
}

module.exports = {
  formatTime: formatTime,
  DoCommand: DoCommand,
  sha1: sha1,
  NewGuid: NewGuid,
  ErrorMessage: ErrorMessage,
  ShowMessage: ShowMessage,
  GetSign: GetSign,
  NotVip: NotVip
}

